package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class ReportServiceImpl  implements ReportService {

    private final OrderMapper orderMapper;
    private final UserMapper userMapper;
    private final WorkspaceService workspaceService;

    /**
     * 统计指定区间内的营业额数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList=new ArrayList<>();//当前集合用于存放起始日期到结束日期的每天日期
        //1.设置起始日期到结束日期
        dateList.add(begin);//存入起始日期
        while (!begin.equals(end)){
            begin=begin.plusDays(1);//起始日期加一天
            dateList.add(begin);//存入集合
        }
        //2.日期集合转字符串
//        StringUtils.join(dateList,",");//把dateList集合元素取出来，并且以逗号分割，最终拼成一个字符串

        //3.遍历日期集合，存入每天营业额
        List<Double> turnoverList=new ArrayList<>();
        for (LocalDate date:dateList){
            //查询date日期对应的营业额数据，营业额是指：状态为“已完成”的订单金额合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//当日起始时间
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//当天借宿时间

            //构造sql查询条件
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover=orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;//判断是否为空
            turnoverList.add(turnover);//存入集合
        }

        //封装返回结果
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 用户统计数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();//当前集合用于存放起始日期到结束日期的每天日期
        //1.设置起始日期到结束日期
        dateList.add(begin);//存入起始日期
        while (!begin.equals(end)){
            begin=begin.plusDays(1);//起始日期加一天
            dateList.add(begin);//存入集合
        }
        List<Integer> newUserList = new ArrayList<>(); //每天新增用户数
        List<Integer> totalUserList = new ArrayList<>(); //每天总用户数

        for (LocalDate date:dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//当日起始时间
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//当天结束时间

            Map map = new HashMap();
            map.put("end",endTime);

            Integer totalUser = userMapper.countByMap(map);//总的用户数量

            map.put("begin",beginTime);
            Integer newUser = userMapper.countByMap(map);//新增用户数量

            totalUserList.add(totalUser);//存入总的用户集合
            newUserList.add(newUser);//存入每天新增用户

        }

        return UserReportVO.
                builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    /**
     * 统计指定时间订单数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();//当前集合用于存放起始日期到结束日期的每天日期
        //1.设置起始日期到结束日期
        dateList.add(begin);//存入起始日期
        while (!begin.equals(end)){
            begin=begin.plusDays(1);//起始日期加一天
            dateList.add(begin);//存入集合
        }
        List<Integer> orderCountList = new ArrayList<>();//每天集合总数
        List<Integer> validOrderCountList = new ArrayList<>();//每天有效集合总数
        //2.查询每天有效订单和总数
        for(LocalDate date:dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//当日起始时间
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//当天结束时间

            //查询每天订单总数
            Integer orderConut = getOrderConut(beginTime, endTime, null);
            orderCountList.add(orderConut);

            //查询每天有效订单数
            Integer validOrderConut = getOrderConut(beginTime, endTime, Orders.COMPLETED);
            validOrderCountList.add(validOrderConut);
        }
        //计算时间区间内的订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        //计算时间区间内的有效订单数量
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //计算订单完成率
        Double orderCompletionRate=0.0;
        if(totalOrderCount!=0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }


        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))//日期
                .orderCountList(StringUtils.join(orderCountList,","))//每日订单数
                .totalOrderCount(totalOrderCount)//订单总数
                .validOrderCountList(StringUtils.join(validOrderCountList,","))//有效订单总数
                .validOrderCount(validOrderCount)//每日有效订单数
                .orderCompletionRate(orderCompletionRate)//订单完成率
                .build()
                ;
    }

    /**
     * 统计指定时间区间内的订单数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);//当日起始时间
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);//当天结束时间
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        //从 salesTop10 列表中提取每个商品的名称，生成一个包含所有商品名称的列表
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        //将商品名称列表 names 转化为以逗号分隔的字符串 nameList。
        String nameList = StringUtils.join(names, ",");
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");
        return SalesTop10ReportVO.
                builder()
                .nameList(nameList)
                .numberList(numberList)
                .build()
                ;
    }

    /**
     * 根据条件统计订单数量
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrderConut(LocalDateTime begin,LocalDateTime end,Integer status){
        Map map=new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);
        return orderMapper.countByMap(map);
    }


    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库，获取营业数据---查询最近三十天的数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);//当前时间的前30天
        LocalDate dateEnd = LocalDate.now().minusDays(1);//昨天

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));


        //2.通过POI将数据写入EXcel文件中
        //获取输入流模板
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");


        try {
            //基于模板文件来创建一个新的excel文件
            XSSFWorkbook ecxel = new XSSFWorkbook(in);

            //获取表格文件的sheet页
            XSSFSheet sheet = ecxel.getSheet("sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin+"至"+dateEnd);

            //获得第四行
            XSSFRow row = sheet.getRow(3);
            //写入营业额
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            //写入订单完成率
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //写入新增用户数
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第五行
            row = sheet.getRow(4);
            //写入有效订单
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //写入评均客单价
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            //把最近30天的数据遍历
            for (int i=0;i<30;i++){
                LocalDate date = dateBegin.plusDays(i);

                //查询某一天的营业数据

                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //从第八行开始遍历
                row= sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());//填充时间
                row.getCell(2).setCellValue(businessData.getTurnover());//写入营业额
                row.getCell(3).setCellValue(businessData.getValidOrderCount());//写入有效订单
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());//写入订单完成率
                row.getCell(5).setCellValue(businessData.getUnitPrice());//写入平均客单价
                row.getCell(6).setCellValue(businessData.getNewUsers());//写入订单新增用户数


            }


            //3.通过输出流将Excel文件下载到客服端浏览器
            ServletOutputStream out = response.getOutputStream();
            ecxel.write(out);


            //关闭资源
            out.flush();
            out.close();
            ecxel.close();
        }catch (IOException e){
            e.printStackTrace();
        }





    }
}
